package com.util;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by Kak on 2020/9/2.
 */
public class MyRealm extends AuthorizingRealm{


    //shiro中的授权实现
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {


        Object principal = principalCollection.getPrimaryPrincipal();
        //根据用户信息查询数据库中的权限
        String userName = (String) principal;
        //创建用户授权信息对象
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //创建权限集合
        Set<String> perms = new HashSet<String>();
        perms.add("stu:select");
        perms.add("stu:update");
        authorizationInfo.setStringPermissions(perms);
        return authorizationInfo;
    }
    //shiro中的认证实现
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {


        //获取用户信息
        String username = (String)authenticationToken.getPrincipal();
        //获取密码
        Object credentials = authenticationToken.getCredentials();
        System.out.println("userName:" + username+"password:"+credentials);
        //根据用户名查询用户对象信息获取用密码
        String userName="kaka";
        String password="1234";
        //将送来用户账号及根据账号查出的密码（凭证）封装成一个AuthenticationInfo对象，返回
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(userName, password, getName());
        //将外部获取的用户信息及凭证信息 封装送给Authenticator对象进行认证
        return simpleAuthenticationInfo;
    }



}